//
//  BDOrderHomeViewController.m
//  BeidouMall
//
//  Created by qie on 16/4/8.
//  Copyright © 2016年 qie. All rights reserved.
//

#import "BDOrderHomeViewController.h"
#import "NinaPagerView.h"
#import "BDTransformViewController.h"
#import "BDOrderFooter.h"
#import "OrderTableViewCell.h"
#import "BDEvaluationViewController.h"
#import "BDOrderDetailViewController.h"
#import "BDRefundViewController.h"

#import "BDNavigationController.h"
#import "BDLoginTableViewController.h"
#import "BDBeidouPayViewController.h"
#import "BDOrderHomeHeaderView.h"
#import "BDOrderNavigationController.h"

#define kPageSize 5

@interface BDOrderHomeViewController () <UITableViewDelegate,UITableViewDataSource,NinaPagerViewDelegate,BDOrderFooterDelegate,OrderTableViewCellDelegate,SimplePopupViewDelegate>
{
    NSArray *_vcsArray;
    NSInteger _curPage;
    NSMutableArray *_OrderList;
    NSUInteger lastTag;
    NSDictionary *statusDic;
    UIViewController *home_vc;
    NSUInteger nowPage;
    NinaPagerView *_ninaPagerView;
    BOOL presentLoginView;
    
    NSString *_tradeID;
    
    SimplePopupView *_popView;
}
@end

@implementation BDOrderHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 处理tableView上面多出来20个像素(是因为自动布局的缘故)
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    self.title = NSLocalizedString(@"Order", nil);
    
    [self tableViewSettings];
    _OrderList = [[NSMutableArray alloc] init];
    
    statusDic = @{@"TO_PAY":NSLocalizedString(@"Wait to pay", nil),
                  @"PAYED":NSLocalizedString(@"Payed orders", nil),
                  @"RECEIVING":NSLocalizedString(@"Picking item", nil),
                  @"SENDING":NSLocalizedString(@"Sending item", nil),
                  @"COMFIRM_RECEIVE":NSLocalizedString(@"Comfirm receive", nil),
                  @"APPLY_REFUND":NSLocalizedString(@"Apply for a refund", nil),
                  @"REFUNDING":NSLocalizedString(@"Refunding", nil),
                  @"REFUNDED":NSLocalizedString(@"Refunded", nil),
                  @"CANCEL":NSLocalizedString(@"Cancelled", nil),
                  @"CLOSED":NSLocalizedString(@"Closed", nil),
                  @"COMFIRM_PAYING":NSLocalizedString(@"Confirming", nil)};
    
    [self setHeaderPopView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"zang"]) {
        [self.navigationController.navigationBar
         setTitleTextAttributes:
         @{NSFontAttributeName:[UIFont fontWithName:@"BZDHT" size:12.0],
           NSForegroundColorAttributeName:RGBColor(51, 51, 51)}];
    } else {
        [self.navigationController.navigationBar
         setTitleTextAttributes:
         @{NSFontAttributeName:[UIFont boldSystemFontOfSize:18.0],
           NSForegroundColorAttributeName:RGBColor(51, 51, 51)}];
    }

    self.navigationController.navigationItem.rightBarButtonItem = nil;
    
    if (self.notRefreshHome) {
        
    } else {
        if (self.selectIndex != 0) {
            UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
            btn.tag = self.selectIndex;
            [_ninaPagerView.pagerView touchAction:btn];
            nowPage = self.selectIndex;
            self.selectIndex = 0;
        } else {
            for (UITableView *tableView in _vcsArray) {
                if (tableView.tag == nowPage + 101) {
                    [tableView.mj_header beginRefreshing];
                    break;
                }
            }
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark Private method

- (void)reloadData:(id) sender andTag:(NSUInteger) tag {
    if (lastTag != tag) {
        _curPage = 0;
    }
    lastTag = tag;
    _curPage = sender == self ? 1 : _curPage + 1;
    NSString *url;
    UITableView *tableView;
    // TO_PAY,PAYED,RECEIVING,SENDING,COMFIRM_RECEIVE,APPLY_REFUND,  ,REFUNDED,CANCEL,CLOSED
    switch (tag) {
        case 101:// 全部
            url = [NSString stringWithFormat:@"%@%@?userId=%@&currentPage=%ld&pageSize=%d",
                   [BDNetworking shareInstance].baseUrl,
                   Order_Query,
                   [BDAccountManagerModel shareInstance].userId,
                   (long)_curPage,
                   kPageSize];
            tableView = self.tableView1;
            break;
        case 102:// 待付款
            url = [NSString stringWithFormat:@"%@%@?status=%@&userId=%@&currentPage=%ld&pageSize=%d",
                   [BDNetworking shareInstance].baseUrl,
                   Order_Query,
                   @"TO_PAY",
                   [BDAccountManagerModel shareInstance].userId,
                   (long)_curPage,
                   kPageSize];
            tableView = self.tableView2;
            break;
        case 103:// 待发货
            url = [NSString stringWithFormat:@"%@%@?status=%@,%@&userId=%@&currentPage=%ld&pageSize=%d",
                   [BDNetworking shareInstance].baseUrl,
                   Order_Query,
                   @"PAYED",@"RECEIVING",
                   [BDAccountManagerModel shareInstance].userId,
                   (long)_curPage,
                   kPageSize];
            tableView = self.tableView3;
            break;
        case 104:// 待收货
            url = [NSString stringWithFormat:@"%@%@?status=%@&userId=%@&currentPage=%ld&pageSize=%d",
                   [BDNetworking shareInstance].baseUrl,
                   Order_Query,
                   @"SENDING",
                   [BDAccountManagerModel shareInstance].userId,
                   (long)_curPage,
                   kPageSize];
            tableView = self.tableView4;
            break;
        case 105:// 已收货
            url = [NSString stringWithFormat:@"%@%@?status=%@&userId=%@&currentPage=%ld&pageSize=%d",
                   [BDNetworking shareInstance].baseUrl,
                   Order_Query,
                   @"COMFIRM_RECEIVE",
                   [BDAccountManagerModel shareInstance].userId,
                   (long)_curPage,
                   kPageSize];
            tableView = self.tableView5;
            break;
        default:
            break;
    }
    if (_curPage == 1) {// 消除没有更多数据的状态
        [tableView.mj_footer resetNoMoreData];
    }
    if (url) {
        [[BDNetworking shareInstance] postWithUrl:url sid:nil method:@"GET" parameters:nil completionHandler:^(NSObject *results, NSError *error) {
            for (UITableView *tableView in _vcsArray) {
                if (tableView.tag == tag) {
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3* NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        if ([tableView.mj_header isRefreshing]) {
                            [tableView.mj_header endRefreshing];
                        }
                        if ([tableView.mj_footer isRefreshing]) {
                            [tableView.mj_footer endRefreshing];
                        }
                    });
                }
            }
            if (error != nil) {
                NSLog(@"tag->订单查询失败:%lu%@",(unsigned long)tag,error);
                if ([[error localizedDescription] isEqualToString:@"登录超时"] && error.code == 401) {
                    [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"Login timeout", nil)];
                    if (!presentLoginView) {
                        presentLoginView = YES;
                        // 清除webViw cookie
                        NSHTTPCookie *cookie;
                        NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
                        for (cookie in [storage cookies])
                        {
                            [storage deleteCookie:cookie];
                        }
                        
                        [BDAccountManagerModel shareInstance].authorization = @"";
                        [BDAccountManagerModel shareInstance].login = NO;
                        UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
                        BDNavigationController *nav_addrVc = [stroyboard instantiateViewControllerWithIdentifier:@"navLoginStoryboardID"];
                        [self presentViewController:nav_addrVc animated:YES completion:nil];
                    }
                }
            } else {
                for (UITableView *tableView in _vcsArray) {
                    if (tableView.tag == tag) {
                        if ([results isKindOfClass:[NSDictionary class]]) {
                            NSLog(@"results = %@",results);
                            NSDictionary *resultDic = (NSDictionary *)results;
                            NSArray *resultList = resultDic[@"objects"];
                            if ([resultList count] > 0) {
//                                tableView.mj_footer.hidden = [resultList count] == kPageSize ? NO : YES;
                                if ([resultList count] < kPageSize) {// 数据不够分页,显示没有更多了
                                    dispatch_async(dispatch_get_main_queue(), ^{
                                        [tableView.mj_footer endRefreshingWithNoMoreData];
                                    });
                                }
                                if (sender == self) {
                                    [_OrderList removeAllObjects];
                                }
                                [_OrderList addObjectsFromArray:resultList];
                            } else {
                                if (_curPage > 1) { // 分页引起的刷新
                                    dispatch_async(dispatch_get_main_queue(), ^{
                                        [tableView.mj_footer endRefreshingWithNoMoreData];
                                    });
                                } else { // 刷新之前的数据应该清零
                                    [_OrderList removeAllObjects];
                                }
                            }
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [tableView reloadData];
                            });
                            
                        }
                        break;
                    }
                }
                
            }
        }];
    }
}

- (void)setTableViewHeader:(UITableView *) tableView withIndex:(NSUInteger) index {
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self reloadData:self andTag:index];
    }];
    if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"zang"]) {
        header.stateLabel.font = [UIFont fontWithName:@"Bzdbt" size:9.0];
    }
    
    [header setTitle:NSLocalizedString(@"Pull down to refresh", nil) forState:MJRefreshStateIdle];
    [header setTitle:NSLocalizedString(@"Release to refresh", nil) forState:MJRefreshStatePulling];
    [header setTitle:NSLocalizedString(@"Loading ...", nil) forState:MJRefreshStateRefreshing];
    // 隐藏时间
    header.lastUpdatedTimeLabel.hidden = YES;
    
    tableView.mj_header = header;
}

- (void)tableViewSettings {
    self.tableView1 = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView2 = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView3 = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView4 = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView5 = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    
    
    NSArray *titleArray =   @[NSLocalizedString(@"All", nil),
                              NSLocalizedString(@"Wait to pay", nil),
                              NSLocalizedString(@"Wait to Express", nil),
                              NSLocalizedString(@"Wait to receive", nil),
                              NSLocalizedString(@"Received", nil)];
    _vcsArray = @[self.tableView1,self.tableView2,self.tableView3,self.tableView4,self.tableView5];
    NSArray *colorArray = @[
                            RGBColor(215, 19, 33), /** 选中的标题颜色 **/
                            RGBColor(51, 51, 51), /** 未选中的标题颜色 **/
                            RGBColor(215, 19, 33), /** 下划线颜色 **/
                            ];
    
    NSUInteger index = 101;
    for (UITableView *tableView in _vcsArray) {
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.tag = index;
        tableView.backgroundColor = RGBColor(238, 238, 238);
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        // 注册刷新头部和尾部
        [self setTableViewHeader:tableView withIndex:index];
        tableView.mj_footer = [MJDIYBackFooter footerWithRefreshingBlock:^{
            [self reloadData:nil andTag:index];
        }];
        
        index++;
    }
    _ninaPagerView = [[NinaPagerView alloc] initWithTitles:titleArray WithVCs:_vcsArray WithColorArrays:colorArray];
    _ninaPagerView.delegate = self;
    [self.view addSubview:_ninaPagerView];
}

- (void)setHeaderPopView {
    NSArray *tmpArray = @[NSLocalizedString(@"home", nil),NSLocalizedString(@"message", nil)];
    NSArray *images = @[@"homeback",@"messageback"];
    //左
    _popView = [[SimplePopupView alloc] initWithFrame:CGRectMake(kScreen_Width - 130.0, 55.0, 120.0, 80.0)
                                         andDirection:PopViewDirectionTop
                                            andTitles:tmpArray
                                            andImages:images
                                       trianglePecent:0.5]; //箭头位于popview中间0.5位置
    [self.navigationController.navigationBar showPopView:_popView AtPoint:CGPointMake(0.5, 0)];//箭头位于button的x=0.y=0.5比例处
    _popView.delegate = self; //需要正式使用时注意代理
}

#pragma mark SimplePopupView delegate

- (void)simplePopupView:(SimplePopupView *)popView clickAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"代理方法，点击了第%ld行",(long)indexPath.row);
    if (indexPath.row == 0) {
        [self dismissViewControllerAnimated:YES completion:nil];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            BDOrderNavigationController *nav = (BDOrderNavigationController *)self.navigationController;
            nav.mTabBarController.selectedIndex = 0;
        });
    } else if (indexPath.row == 1) {
        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"Still in process", nil)];
    }
}

#pragma mark - NinaPagerViewDelegate

- (void)refreshTableView:(NSUInteger)page {
    nowPage = page;
    for (UITableView *tableView in _vcsArray) {
        if (tableView.tag == page + 101) {
            [_OrderList removeAllObjects];// 不然之前的数据会填入tableView
            [tableView.mj_footer resetNoMoreData];// 还原为普通状态
            [tableView.mj_header beginRefreshing];
        }
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (_OrderList.count > 0) {
        return _OrderList.count;
    } else {
        return 1;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_OrderList.count > 0) {
        NSArray *goodList = _OrderList[section][@"orderCommodities"];
        return goodList.count;
    } else {
        return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_OrderList.count > 0) {
        OrderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"orderCell"];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"OrderCell" owner:nil options:nil] lastObject];
        }
        
        cell.delegate = self;
        cell.backgroundColor = RGBColor(245, 245, 245);
        
        NSArray *goodList = _OrderList[indexPath.section][@"orderCommodities"];
        // 商品图片
        NSString *storeImageUrl = goodList[indexPath.row][@"commodity"][@"icon"];
        UIImageView *storeImageView = (UIImageView *)[cell viewWithTag:101];
        if (![storeImageUrl isEqual:[NSNull null]]) {
            NSInteger width = storeImageView.width * 2;
            NSInteger height = storeImageView.height * 2;
            storeImageUrl = [NSString stringWithFormat:@"%@?dp_cmd=/imageView2/mode/2/w/%ld/h/%ld/",storeImageUrl,(long)width,(long)height];
            [storeImageView sd_setImageWithURL:[NSURL URLWithString:storeImageUrl] placeholderImage:[UIImage imageNamed:@"image_empty"]];
        }
        // 商品名称
        UITextView *goodDescTextView = (UITextView *)[cell viewWithTag:102];
        NSString *goodDesc = goodList[indexPath.row][@"commodity"][@"name"];
        if (![goodDesc isEqual:[NSNull null]]) {
            goodDescTextView.text = goodDesc;
        }
        // 商品现价
        UILabel *priceNowLabel = (UILabel *)[cell viewWithTag:103];
        NSString *goodNowPrice = goodList[indexPath.row][@"price"];
        if (![goodNowPrice isEqual:[NSNull null]]) {
            priceNowLabel.text = [NSString stringWithFormat:@"%@¥%.2f",NSLocalizedString(@"Price", nil),[goodNowPrice floatValue]];
        }
        // 商品个数
        UILabel *numLabel = (UILabel *)[cell viewWithTag:104];
        NSString *goodNum = goodList[indexPath.row][@"num"];
        if (![goodNum isEqual:[NSNull null]]) {
            numLabel.text = [NSString stringWithFormat:@"%@x%ld",NSLocalizedString(@"OrderAmount", nil),(long)[goodNum integerValue]];
        }
        // 申请退货
        UIButton *refundBtn = [(UIButton *)cell viewWithTag:105];
        [refundBtn setTitle:NSLocalizedString(@"Apply for a refund", nil) forState:UIControlStateNormal];
        NSString *orderStatus = _OrderList[indexPath.section][@"status"];
        NSString *goodStatus = goodList[indexPath.row][@"status"];
        if ([orderStatus isEqualToString:@"TO_PAY"] ||
            [orderStatus isEqualToString:@"CLOSED"] ||
            [orderStatus isEqualToString:@"CANCEL"]) {
            [refundBtn setHidden:YES];
        } else {
            [refundBtn setHidden:NO];
        }
        
        if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"en"]) {
            cell.buttonWidthConstrains.constant = 100.0;
            refundBtn.titleLabel.font = [UIFont systemFontOfSize:10.0];
        } else if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"zh"]) {
            cell.buttonWidthConstrains.constant = 66.0;
        }
        
        if ([goodStatus isEqualToString:@"CLOSED"] || [goodStatus isEqualToString:@"CLOSE"]) {// 关闭退款 此时不显示退款按钮
            [refundBtn setHidden:YES];
        }
        
        if ([goodStatus isEqualToString:@"NORMAL"] ||
            [goodStatus isEqualToString:@"REFUSE_REFUND"]) {// 正常状态 拒绝退款
            [refundBtn setTitle:NSLocalizedString(@"Apply for a refund", nil) forState:UIControlStateNormal];// 申请退款
        } else {
            NSString *statusStr;
            if ([goodStatus isEqualToString:@"APPLY_REFUND"]) {
                statusStr = NSLocalizedString(@"Have applied a refund", nil);// 已申请退货
            }
            if ([goodStatus isEqualToString:@"REFUNDING"]) {
                statusStr = NSLocalizedString(@"Refunding", nil);// 退款中
            }
            if ([goodStatus isEqualToString:@"REFUND"]) {
                statusStr = NSLocalizedString(@"Refunded", nil);// 已退款
            }
            [refundBtn setTitle:statusStr forState:UIControlStateNormal];
            
        }
        return cell;
    } else {
        OrderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"orderNoneCell"];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"OrderNoneCell" owner:nil options:nil] lastObject];
        }
        
        UILabel *label = (UILabel *)[cell viewWithTag:101];
        label.text = NSLocalizedString(@"No order information", nil);
        
        return cell;
    }
}

#pragma mark - Tableview delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat cellHeight = 100.0;
    for (UITableView *tableView in _vcsArray) {
        if (tableView.tag == nowPage + 101) {
            tableView.scrollEnabled = _OrderList.count > 0 ? YES : NO;
        }
    }
    if (_OrderList.count > 0) {
        NSArray *goodList = _OrderList[indexPath.section][@"orderCommodities"];
        NSString *goodDesc = goodList[indexPath.row][@"commodity"][@"name"];
        if (![goodDesc isEqual:[NSNull null]]) {
            cellHeight = [goodDesc boundingHeightWithSize:CGSizeMake(kScreen_Width - 104.0, CGFLOAT_MAX) font:[UIFont systemFontOfSize:13.0] lineSpace:8.0] + 55;
            cellHeight = cellHeight < 100 ? 100 : cellHeight;
            NSLog(@"goodDesc %@ \n cellHeight = %f",goodDesc,cellHeight);
        }
    }
    return _OrderList.count > 0 ? cellHeight : kScreen_Height - 64 - .0675 * kScreen_Height;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (_OrderList.count > 0) {
        NSString *storeName = _OrderList[section][@"store"][@"name"];
        CGFloat labelHeight = 17.0;
        if (![storeName isEqual:[NSNull null]]) {
            labelHeight = [storeName boundingHeightWithSize:CGSizeMake(kScreen_Width - 91.0, CGFLOAT_MAX) font:[UIFont systemFontOfSize:14.0] lineSpace:4.0];
        }
        if (labelHeight <= 17.0) {
            labelHeight = 17.0;
        }
        return labelHeight + 18.0;
    }
    return 0.1;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (_OrderList.count > 0) {
        UIView *header = [[[NSBundle mainBundle] loadNibNamed:@"orderHeader" owner:nil options:nil] lastObject];
        
        // 商店名称
        NSString *storeName = _OrderList[section][@"store"][@"name"];
        if (![storeName isEqual:[NSNull null]]) {
            ((UILabel *)[header viewWithTag:101]).text = storeName;
        }
        // 订单当前状态
        UILabel *statusLabel = (UILabel *)[header viewWithTag:102];
        NSString *orderStatus = _OrderList[section][@"status"];
        
        if ([statusDic valueForKey:orderStatus] &&
            ![orderStatus isEqual:[NSNull null]]) {
            statusLabel.text = statusDic[orderStatus];
        }
        
        return header;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return _OrderList.count > 0 ? 60.0 : 0.1;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (_OrderList.count > 0) {
        BDOrderFooter *footer = [[[NSBundle mainBundle] loadNibNamed:@"orderFooter" owner:nil options:nil] lastObject];
        footer.tag = section;
        footer.delegate = self;
        // 合计
        UILabel *totalPriceLabel = (UILabel *)[footer viewWithTag:111];
        //        totalPriceLabel.text = NSLocalizedString(@"Total", nil);
        NSInteger goodTotalNumber = 0;
        NSArray *goodList = _OrderList[section][@"orderCommodities"];
        if (![goodList isEqual:[NSNull null]] &&
            [goodList isKindOfClass:[NSArray class]]) {
            for (NSDictionary *goodDic in goodList) {
                NSInteger num = [goodDic[@"num"] integerValue];
                goodTotalNumber += num;
            }
            
            NSString *commodityPrice = _OrderList[section][@"commodityPrice"];
            NSString *expressPrice = _OrderList[section][@"expressPrice"];
            if (![commodityPrice isEqual:[NSNull null]] &&
                ![expressPrice isEqual:[NSNull null]]) {
                totalPriceLabel.text = [NSString stringWithFormat:@"共%ld件商品 合计：%.2f元（含运费¥%.2f）",
                                        (long)goodTotalNumber,
                                        [commodityPrice floatValue] + [expressPrice floatValue]
                                        ,[expressPrice floatValue]];
            }
        }
        
        
        NSString *orderStatus = _OrderList[section][@"status"];
        // 商品价格
//        UILabel *goodPriceLabel = (UILabel *)[footer viewWithTag:107];
//        NSString *commodityPrice = _OrderList[section][@"commodityPrice"];
//        NSString *expressPrice = _OrderList[section][@"expressPrice"];
//        if (![commodityPrice isEqual:[NSNull null]] &&
//            ![expressPrice isEqual:[NSNull null]] &&
//            [goodPriceLabel isKindOfClass:[UILabel class]]) {
//            goodPriceLabel.text = [NSString stringWithFormat:@"¥ %.2f",[commodityPrice floatValue] + [expressPrice floatValue]];
//        }
        // 右下角按钮
        UIButton *button1 = (UIButton *)[footer viewWithTag:108];
        UIButton *button2 = (UIButton *)[footer viewWithTag:109];
        button1.hidden = NO;
        button2.hidden = NO;
        if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"en"]) {
            footer.firstButtonConstraint.constant = 100.0;
            footer.secondButtonConstraint.constant = 100.0;
            button1.titleLabel.font = [UIFont systemFontOfSize:10.0];
            button2.titleLabel.font = [UIFont systemFontOfSize:10.0];
        } else if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"zh"]) {
            footer.firstButtonConstraint.constant = 66.0;
            footer.secondButtonConstraint.constant = 66.0;
        }
        if ([statusDic valueForKey:orderStatus] &&
            ![orderStatus isEqual:[NSNull null]]) {
            if ([orderStatus isEqualToString:@"TO_PAY"]) {// 待付款
                button1.hidden = YES;
                [button2 setTitle:NSLocalizedString(@"Pay", nil) forState:UIControlStateNormal];// 付款
                button2.hidden = NO;
            }
            if ([orderStatus isEqualToString:@"PAYED"] ||
                [orderStatus isEqualToString:@"RECEIVING"]) {// 待发货
                button1.hidden = YES;
                button2.hidden = YES;
            }
            if ([orderStatus isEqualToString:@"SENDING"]) {// 待收货
                [button1 setTitle:NSLocalizedString(@"Check Express", nil) forState:UIControlStateNormal];// 查看物流
                [button2 setTitle:NSLocalizedString(@"Comfirm receive btntitle", nil) forState:UIControlStateNormal];// 确认收货
                [button2 setBackgroundImage:[UIImage imageNamed:@"order_roundRectButton3"] forState:UIControlStateNormal];
                [button2 setTitleColor:RGBColor(215, 19, 22) forState:UIControlStateNormal];
            }
            if ([orderStatus isEqualToString:@"COMFIRM_RECEIVE"]) {// 已收货
                [button1 setTitle:NSLocalizedString(@"Check Express", nil) forState:UIControlStateNormal];// 查看物流
                [button2 setTitle:NSLocalizedString(@"Comments", nil) forState:UIControlStateNormal];// 查看评论
                [button2 setBackgroundImage:[UIImage imageNamed:@"order_roundRectButton3"] forState:UIControlStateNormal];
                [button2 setTitleColor:RGBColor(215, 19, 22) forState:UIControlStateNormal];
            }
            if ([orderStatus isEqualToString:@"CANCEL"]) {// 已取消
                button1.hidden = YES;
                button2.hidden = YES;
            }
            if ([orderStatus isEqualToString:@"CLOSED"]) {// 已关闭
                button1.hidden = YES;
                button2.hidden = YES;
            }
            if ([orderStatus isEqualToString:@"COMFIRM_PAYING"]) {// 确认付款中
                button1.hidden = YES;
                button2.hidden = YES;
            }
        }
        
        return footer;
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_OrderList.count > 0) {
        NSDictionary *dic = _OrderList[indexPath.section];
        UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
        
        BDOrderDetailViewController *detailVC = [stroyboard instantiateViewControllerWithIdentifier:@"OrderDetailStoryboardID"];
        detailVC.order = dic;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}

#pragma mark - BDOrderFooterDelegate

- (void)pushToNewViewController:(UIView *)sender name:(NSString *)name {
    UIView *superView = sender.superview;
    while (![superView isKindOfClass:[BDOrderFooter class]]) {
        superView = superView.superview;
    }
    BDOrderFooter *footer = (BDOrderFooter *)superView;
    
    NSString *orderId = _OrderList[footer.tag][@"orderId"];
    NSArray *commodities = _OrderList[footer.tag][@"orderCommodities"];
    
    UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    if ([name isEqualToString:NSLocalizedString(@"Check Express", nil)]) {
        NSString *expressType = _OrderList[footer.tag][@"expressType"];
        if (![expressType isEqual:[NSNull null]]) {
            if ([expressType isEqualToString:@"ONESELF"]) {
                [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"Item is self-pick up,no express info", nil)];
                return;
            }
        }
        BDTransformViewController *trans_vc = [stroyboard instantiateViewControllerWithIdentifier:@"TransformStoryboardID"];
        trans_vc.orderId = orderId;
        [self.navigationController pushViewController:trans_vc animated:YES];
    }
    if ([name isEqualToString:NSLocalizedString(@"Comments", nil)]) {
        BDEvaluationViewController *eva_vc = [stroyboard instantiateViewControllerWithIdentifier:@"EvaluationStoryboardID"];
        eva_vc.orderId = orderId;
        eva_vc.commodities = commodities;
        [self.navigationController pushViewController:eva_vc animated:YES];
    }
    
}

- (void)confirmReceive:(UIView *)sender {
    UIView *superView = sender.superview;
    while (![superView isKindOfClass:[BDOrderFooter class]]) {
        superView = superView.superview;
    }
    BDOrderFooter *footer = (BDOrderFooter *)superView;
    for (UITableView *tableView in _vcsArray) {
        if (tableView.tag == nowPage + 101) {
            
            NSString *orderId = _OrderList[footer.tag][@"orderId"];
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view withText:NSLocalizedString(@"Wait for checking", nil)];
            
            NSString *url = [NSString stringWithFormat:@"%@%@?orderId=%@",[BDNetworking shareInstance].baseUrl,Order_Receive,orderId];
            [[BDNetworking shareInstance] postWithUrl:url sid:nil method:@"PUT" parameters:nil completionHandler:^(NSObject *results, NSError *error) {
                if (error != nil) {
                    NSLog(@"确认收货失败:%@",error);
                    hud.labelText = NSLocalizedString(@"Checking failed", nil);
                    [hud hideAfterDelay:0.5];
                } else {
                    [hud hideAfterDelay:0.5];
                    hud.labelText = NSLocalizedString(@"Checking success", nil);
                    NSLog(@"result = %@",results);
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5* NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [tableView.mj_header beginRefreshing];
                    });
                }
            }];
            
            break;
        }
    }
}

- (void)payOrder:(UIButton *)sender {
    UIView *superView = sender.superview;
    while (![superView isKindOfClass:[BDOrderFooter class]]) {
        superView = superView.superview;
    }
    BDOrderFooter *footer = (BDOrderFooter *)superView;
    NSString *orderId = _OrderList[footer.tag][@"orderId"];
    NSString *payType = _OrderList[footer.tag][@"payType"];
    
    if (![WXApi isWXAppInstalled] && [payType isEqualToString:@"WECHAT"]) {
        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"WeChat not installed cannot pay", nil)];
    } else {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view withText:NSLocalizedString(@"paying...", nil)];
        
        NSString *url = [NSString stringWithFormat:@"%@%@?orderId=%@",[BDNetworking shareInstance].baseUrl,OrderPay,orderId];
        [[BDNetworking shareInstance] postWithUrl:url sid:nil method:@"GET" parameters:nil completionHandler:^(NSObject *results, NSError *error) {
            if (error != nil) {
                NSLog(@"付款失败:%@",error);
                hud.labelText = @"付款失败";
                [hud hideAfterDelay:0.5];
            } else {
                [hud hideAfterDelay:0.1];
                NSLog(@"result = %@",results);
                NSString *data = (NSString *)results;
                if ([payType isEqualToString:@"ALIPAY"]) {
                    [self aliPayWithOrder:data Callback:^(NSDictionary *results) {
                        NSLog(@"支付结果reslut = %@",results);
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSInteger code = [[results valueForKey:@"resultStatus"] integerValue];
                            NSString *type;
                            if (code == 9000) {
                                type = @"success";
                                NSString *tradeID = [self dataProcess:data];
                                if (![tradeID isEqual:[NSNull null]]) {// 成功后需要调用付款成功通知
                                    NSString *url = [NSString stringWithFormat:@"%@%@?tradeId=%@",[BDNetworking shareInstance].baseUrl,PaySuccess,tradeID];
                                    [[BDNetworking shareInstance] postWithUrl:url sid:nil method:@"PUT" parameters:nil completionHandler:^(NSObject *results, NSError *error) {
                                        if (error != nil) {
                                            NSLog(@"付款成功通知失败:%@",error);
                                        } else {
                                            NSLog(@"result = %@",results);
                                        }
                                    }];
                                    [MBProgressHUD showToast:self.view withText:@"付款成功"];
                                }
                            } else {
                                type = @"fail";
                                [MBProgressHUD showToast:self.view withText:@"付款失败"];
                            }
                        });
                    }];
                } else if ([payType isEqualToString:@"WECHAT"]) {
                    NSDictionary *dic = [self dataProcess2:data];
                    //调起微信支付
                    PayReq* req = [[PayReq alloc] init];
                    req.openID = [dic objectForKey:@"appid"];
                    req.partnerId = [dic objectForKey:@"partnerid"];
                    req.prepayId = [dic objectForKey:@"prepayid"];
                    req.nonceStr = [dic objectForKey:@"noncestr"];
                    NSNumber *time = [dic objectForKey:@"timestamp"];
                    req.timeStamp = [time unsignedIntValue];
                    req.package = [dic objectForKey:@"package"];
                    req.sign = [dic objectForKey:@"sign"];
                    [WXApi sendReq:req];
                }
            }
        }];
    }
}

- (void)aliPayWithOrder:(NSString *) order Callback:(void(^)(NSDictionary *results))callBack {// 支付宝回调
    //应用注册scheme 便于支付结束后重新打开客户端
    NSString *appScheme = @"BeidouMall";
    NSLog(@"签名字符串:%@",order);
    [[AlipaySDK defaultService] payOrder:order fromScheme:appScheme callback:^(NSDictionary *resultDic) {
        callBack(resultDic);
    }];
}

- (NSString *)dataProcess:(NSString *)string {// 从字符串中取数据
    NSArray *array = [string componentsSeparatedByString:@"&"];
    for (NSString *str in array) {// out_trade_no
        NSArray *array = [str componentsSeparatedByString:@"="];
        NSString *key = array[0];
        if ([key isEqualToString:@"out_trade_no"]) {
            return array[1];
        }
    }
    return nil;
}

- (NSDictionary *)dataProcess2:(NSString *)string {// 从字符串中取数据
    NSArray *array = [string componentsSeparatedByString:@"&"];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    for (NSString *str in array) {// out_trade_no
        NSArray *array = [str componentsSeparatedByString:@"="];
        NSString *key = array[0];
        NSString *value;
        if ([key isEqualToString:@"package"]) {
            value = [NSString stringWithFormat:@"%@=%@",array[1],array[2]];
        } else {
            if ([key isEqualToString:@"out_trade_no"]) {
                _tradeID = array[1];
            }
            value = array[1];
        }
        [dic setValue:value forKey:key];
    }
    return dic;
}

- (void)weixinPayResult:(id) sender {
    NSLog(@"%@",sender);
    NSNotification *notificaion = (NSNotification *)sender;
    NSDictionary *dic = notificaion.userInfo;
    
    NSInteger code = [[dic valueForKey:@"errCode"] integerValue];
    NSString *type;
    if (code == 0) {
        type = @"success";
        NSString *url = [NSString stringWithFormat:@"%@%@?tradeId=%@",[BDNetworking shareInstance].baseUrl,PaySuccess,_tradeID];
        [[BDNetworking shareInstance] postWithUrl:url sid:nil method:@"PUT" parameters:nil completionHandler:^(NSObject *results, NSError *error) {
            if (error != nil) {
                NSLog(@"付款成功通知失败:%@",error);
            } else {
                NSLog(@"result = %@",results);
                [MBProgressHUD showToast:self.view withText:@"付款成功"];
            }
        }];
    } else {
        type = @"fail";
        [MBProgressHUD showToast:self.view withText:@"付款失败"];
    }
}

#pragma mark OrderTableViewCellDelegate

- (void)applyRefund:(UIView *)sender {
    UIView *superView = sender.superview;
    while (![superView isKindOfClass:[UITableViewCell class]]) {
        superView = superView.superview;
    }
    UITableViewCell *cell = (UITableViewCell *)superView;
    for (UITableView *tableView in _vcsArray) {
        if (tableView.tag == nowPage + 101) {
            NSIndexPath *indexPath = [tableView indexPathForCell:cell];
            NSArray *goodList = _OrderList[indexPath.section][@"orderCommodities"];
            UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
            BDRefundViewController *refund_vc = [stroyboard instantiateViewControllerWithIdentifier:@"RefunStoryboardID"];
            refund_vc.goodList = goodList;
            refund_vc.index = indexPath.row;
            refund_vc.block = ^(NSString *str){
                if ([str isEqualToString:@"success"]) {
                    
                }
            };
            [self.navigationController pushViewController:refund_vc animated:YES];
        }
    }
}


#pragma mark - IBActions

- (IBAction)backButtonPressed:(UIBarButtonItem *)sender {
    if (self.jumpToHomepage) {// 在返回之后的页面(支付页面)跳到个人中心
        self.block(@"success");
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

//- (IBAction)homeButtonPressed:(UIBarButtonItem *)sender {
//    self.block(@"success");
//    [self dismissViewControllerAnimated:YES completion:nil];
//}

- (IBAction)homeRightButtonPressed:(UIButton *)sender {
    [_popView show:CGRectMake(kScreen_Width - 130.0, 55.0, 120.0, 80.0)];
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
